package com.xkdx.caipiao.my;

import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.xkdx.caipiao.R;
import com.xkdx.caipiao.RechargeActivity;
import com.xkdx.caipiao.ThreadActivity;
import com.xkdx.caipiao.module.network.AbsModule;
import com.xkdx.caipiao.presistence.flowrechanrge.FlowreChanrgeAction;
import com.xkdx.caipiao.presistence.flowrechanrge.FlowreChanrgeModule;
import com.xkdx.caipiao.presistence.flowrechanrge.FlowreChanrgePresistence;
import com.xkdx.caipiao.presistence.flowrechanrgeorder.FlowreChanrgeorderAction;
import com.xkdx.caipiao.presistence.flowrechanrgeorder.FlowreChanrgeorderInfo;
import com.xkdx.caipiao.presistence.flowrechanrgeorder.FlowreChanrgeorderModule;
import com.xkdx.caipiao.presistence.flowrechanrgeorder.FlowreChanrgeorderPresistence;
import com.xkdx.caipiao.statics.IConstants;
import com.xkdx.caipiao.util.HideKeyboard;
import com.xkdx.caipiao.util.IsMobileNum;
import com.xkdx.caipiao.util.Md5Utils;
import com.xkdx.guangguang.LoginActivity;
import com.xkdx.guangguang.util.PhoneUtil;

public class FlowRechargeActivity extends ThreadActivity implements
		OnClickListener {
	MyAdapter adapter;
	boolean isVisiable = false;
	boolean isdakai = false;
	boolean isnull = false;
	boolean isShenglei = false;
	private List<FlowreChanrgeorderInfo> list;
	FlowreChanrgeAction action1;
	FlowreChanrgeModule module1;
	FlowreChanrgePresistence presistence1;
	FlowreChanrgeorderAction action;
	FlowreChanrgeorderModule module;
	FlowreChanrgeorderPresistence presistence;
	private TextView tv_nationwide, tv_province, tv_money, tv_flow,liuliangleixing,tv_phone_type;
	private EditText et_phone_num;
	private LinearLayout ll_leixing, ll_money,ll_record,quanguo_or_shennei;
	private ListView lv_list, lv_list2,lv_list3;
//	public static LoginInfo loginInfo;
	private Button sure_pay;
	private String mobileno;
	private String proid;
	private String devicetype = "2";
	private String code = "1";
	private int count = 0;
	
	private List<String> list3;
	
	boolean lock = false;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_flowrecharge_caipiao);
		init();
	}

	private void init() {
		et_phone_num = (EditText) findViewById(R.id.et_phone_num);
		et_phone_num.addTextChangedListener(watcher);
		tv_nationwide = (TextView) findViewById(R.id.tv_nationwide);
		tv_nationwide.setBackgroundResource(R.drawable.bg_province_red_caipiao);
		tv_nationwide.setOnClickListener(this);
		tv_province = (TextView) findViewById(R.id.tv_province);
		tv_province.setOnClickListener(this);
		tv_flow = (TextView) findViewById(R.id.tv_flow);
		sure_pay = (Button) findViewById(R.id.sure_pay);
		sure_pay.setOnClickListener(this);
		liuliangleixing = (TextView) findViewById(R.id.liuliangleixing);
		tv_phone_type = (TextView) findViewById(R.id.phone_type);
		tv_money = (TextView) findViewById(R.id.tv_money);
		ll_money = (LinearLayout) findViewById(R.id.ll_money);
		ll_money.setOnClickListener(this);
		quanguo_or_shennei = (LinearLayout) findViewById(R.id.quanguo_or_shennei);
		quanguo_or_shennei.setOnClickListener(this);
		ll_record = (LinearLayout) findViewById(R.id.ll_record);
		ll_record.setOnClickListener(this);
		lv_list2 = (ListView) findViewById(R.id.lv_list2);
		lv_list3 = (ListView) findViewById(R.id.list_view_3);
		fillListView3();
		lv_list2.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
					long arg3) {
				FlowreChanrgeorderInfo info = (FlowreChanrgeorderInfo) adapter
						.getItem(arg2);
				
				float mon1 = Float.valueOf(info.getValue()) / 100;
				DecimalFormat df = new DecimalFormat("#0.00");
				tv_money.setText("售价 " + "￥"+String.valueOf(df.format(mon1)));
				tv_flow.setText(info.getFlow());
				lv_list2.setVisibility(View.GONE);
				proid = info.getId();
				// 如果点击的这个是红的将其改变为白色的
				/*
				 * if (listmodule.list.get(arg2).isChecked) {
				 * listmodule.list.get(arg2).isChecked = false; } else {//
				 * 如果点击的是白的，先将所有变白 for (CostListInfo hb : listmodule.list) {
				 * hb.isChecked = false; } listmodule.list.get(arg2).isChecked =
				 * true; } adapter.notifyDataSetChanged();
				 */

			}
		});
		lv_list3.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
					long arg3) {
				String value = list3.get(arg2);
				liuliangleixing.setText(value);
				lv_list3.setVisibility(View.GONE);
				proid = "0";
				tv_money.setText("");
				tv_flow.setText("");
				if(value.equals("全国")) {
					if(lock == true){
						adapter = new MyAdapter(module.list1);
						lv_list2.setAdapter(adapter);
					}
				} else {
					if (mobileno!=null) {
						adapter = new MyAdapter(module.list);
						lv_list2.setAdapter(adapter);
					}else {
						Toast.makeText(FlowRechargeActivity.this, "请先输入手机号码", 0).show();
					}
				}
			}
		});
	}
	
	private void fillListView3() {
		list3 = new ArrayList<String>();
		list3.add("全国");
		list3.add("省内");
		MyAdapter2 adapter = new MyAdapter2(list3);
		lv_list3.setAdapter(adapter);
	}

	TextWatcher watcher = new TextWatcher() {
		private CharSequence temp;

		@Override
		public void onTextChanged(CharSequence arg0, int arg1, int arg2,
				int arg3) {
			temp = arg0;

		}

		@Override
		public void beforeTextChanged(CharSequence arg0, int arg1, int arg2,
				int arg3) {
			// TODO Auto-generated method stub

		}

		@Override
		public void afterTextChanged(Editable edt) {
			if (et_phone_num.getText().length() == 11) {
				mobileno = et_phone_num.getText().toString();
				startThread();
			}
			
			String phone = edt.toString();
            //判断是手机，则开始查询信息
            if (IsMobileNum.isMobileNum(phone)) {
                count++;
                PhoneTask phoneTask = new PhoneTask(count, phone);
                phoneTask.execute();
            }

		}
	};

	@Override
	public void showOnPost(HashMap<String, AbsModule> result) {
		dataLoadDialog.dismiss();
		if (result.containsKey("0")) {
			isnull = true;
			ArrayList<FlowreChanrgeorderInfo> tempList;
			if(module.list1 != null && module.list1.size() >0){
				adapter = new MyAdapter(module.list1);
				tempList = module.list1;
				liuliangleixing.setText("全国");
			} else {
				tempList = module.list;
				liuliangleixing.setText("省内");
				adapter = new MyAdapter(module.list);
			}
			if(tempList != null && tempList.size() >0 ){
				FlowreChanrgeorderInfo info = tempList.get(0);
				float mon1 = Float.valueOf(info.getValue()) / 100;
				DecimalFormat df = new DecimalFormat("#0.00");
				tv_money.setText("￥"+String.valueOf(df.format(mon1)));
				tv_flow.setText(info.getFlow());
				lv_list2.setVisibility(View.GONE);
				proid = info.getId();
			}
			lv_list2.setAdapter(adapter);
			lock = true;
			if (isVisiable == true) {//充值的返回
				code = module1.code;
				if ("0000".equals(code)) {
					Toast.makeText(FlowRechargeActivity.this, "提交成功", 1).show();
				} else if ("1014".equals(code)) {
					Toast.makeText(FlowRechargeActivity.this, "金额不足，请先充值", 1)
							.show();
					Intent intent = new Intent(this, RechargeActivity.class);
					startActivity(intent);
				} else if("5004".equals(code)) {
					setLogin();
					Toast.makeText(FlowRechargeActivity.this, "登录失效", 1).show();
				} else  {
					Toast.makeText(FlowRechargeActivity.this, "充值失败", 1).show();
				}
			}
		}

	}
	
	class PhoneTask extends AsyncTask<String, Integer, String> {
        int num;
        String phone;

        public PhoneTask(int num, String phone) {
            this.num = num;
            this.phone = phone;
        }

        @Override
        protected String doInBackground(String... arg0) {
            String result = PhoneUtil.getBasicInfo(phone);
            return result;
        }

        @Override
        protected void onPostExecute(String result) {
            Log.i("phone info is===>", result);
            String arr[] = result.split(" ");
            String lastPart = arr[arr.length - 1];
            if (lastPart.indexOf("联通") > 0) {
                int end = lastPart.indexOf("联通") + 2;
                result = lastPart.substring(0, end);
            } else if (lastPart.indexOf("移动") > 0) {
                int end = lastPart.indexOf("移动") + 2;
                result = lastPart.substring(0, end);
            } else if (lastPart.indexOf("电信") > 0) {
                int end = lastPart.indexOf("电信") + 2;
                result = lastPart.substring(0, end);
            }
            if (num == count) {
                tv_phone_type.setText(result);
            }
        }

    }

	class Holder {
		TextView tv_ye;

	}

	class MyAdapter extends BaseAdapter {

		private List<FlowreChanrgeorderInfo> list2 = new ArrayList<FlowreChanrgeorderInfo>();

		public MyAdapter(List<FlowreChanrgeorderInfo> list2) {
			if(list2 != null) {
				this.list2 = list2;
			}
		}

		public int getCount() {
			return list2.size();
		}

		@Override
		public Object getItem(int position) {
			return list2.get(position);
		}

		@Override
		public long getItemId(int position) {
			return position;
		}

		@Override
		public View getView(final int position, View convertView,
				ViewGroup parent) {
			Holder holder = null;
			if (convertView == null) {
				holder = new Holder();
				convertView = LayoutInflater.from(getApplicationContext())
						.inflate(R.layout.flow_money_caipiao, null);

				holder.tv_ye = (TextView) convertView.findViewById(R.id.tv_ye);

				convertView.setTag(holder);
			} else {
				holder = (Holder) convertView.getTag();
			}

			holder.tv_ye.setText(list2.get(position).getFlow());
			return convertView;
		}

	}
	
	class Holder2 {
		TextView tv_ye;

	}

	class MyAdapter2 extends BaseAdapter {

		private List<String> list3 = new ArrayList<String>();

		public MyAdapter2(List<String> list3) {
			if(list3 != null) {
				this.list3 = list3;
			}
		}

		public int getCount() {
			return list3.size();
		}

		@Override
		public Object getItem(int position) {
			return list3.get(position);
		}

		@Override
		public long getItemId(int position) {
			return position;
		}

		@Override
		public View getView(final int position, View convertView,
				ViewGroup parent) {
			Holder holder = null;
			if (convertView == null) {
				holder = new Holder();
				convertView = LayoutInflater.from(getApplicationContext())
						.inflate(R.layout.flow_money_caipiao, null);

				holder.tv_ye = (TextView) convertView.findViewById(R.id.tv_ye);

				convertView.setTag(holder);
			} else {
				holder = (Holder) convertView.getTag();
			}

			holder.tv_ye.setText(list3.get(position));
			return convertView;
		}

	}

	@Override
	public void startThread() {
		if (!(dataLoadDialog.isShowing())) {
			dataLoadDialog.show();
			dataLoadDialog.setContentView(R.layout.progressbar_caipiao);
		}
		isVisiable = false;
		action = new FlowreChanrgeorderAction(mobileno);
		module = new FlowreChanrgeorderModule();
		presistence = new FlowreChanrgeorderPresistence(this);
		presistence.setActitons(action);
		presistence.setModule(module);
		presistence.execute();

	}

	public void startThreadFlow() {
		if (!(dataLoadDialog.isShowing())) {
			dataLoadDialog.show();
			dataLoadDialog.setContentView(R.layout.progressbar_caipiao);
			isVisiable = true;
//			LoginInfo info = getLoginInfo();
			String md5 = usrSP.getId() + usrSP.getLogintoken() + IConstants.key;
			String signcode = Md5Utils.md5(md5);
			action1 = new FlowreChanrgeAction(usrSP.getId(),
					usrSP.getLogintoken(), devicetype, proid, mobileno, signcode);
			module1 = new FlowreChanrgeModule();
			presistence1 = new FlowreChanrgePresistence(this);
			presistence1.setActitons(action1);
			presistence1.setModule(module1);
			presistence1.execute();

		}
	}

	@Override
	public void onBackClick(View view) {
		finish();

	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.ll_money:
			HideKeyboard.hideKeyboard(FlowRechargeActivity.this);
			if (isdakai) {
				isdakai = false;
				lv_list2.setVisibility(View.GONE);
			}else {
				isdakai = true;
				lv_list2.setVisibility(View.VISIBLE);
			}
			
			break;
		case R.id.quanguo_or_shennei :
			if (isShenglei) {
				isShenglei = false;
				lv_list3.setVisibility(View.GONE);
			}else {
				isShenglei = true;
				lv_list3.setVisibility(View.VISIBLE);
			}
			break;
		case R.id.sure_pay:
			boolean isnum = IsMobileNum.isMobileNum(mobileno);
//			String info = IsMobileNum.isMobileInfo(mobileno);
			if ("0".equals(proid)) {
				Toast.makeText(FlowRechargeActivity.this, "请选择流量面额", 0).show();
				return;
			}
			if ("".equals(mobileno)) {
				Toast.makeText(FlowRechargeActivity.this, "手机号码不能为空", 0).show();
				return;
			}
			if (isnum == false) {
				Toast.makeText(FlowRechargeActivity.this, "请输入正确的手机号码", 0)
						.show();
				return;
			}
//			if ("移动".equals(info) || "电信".equals(info)) {
//				Toast.makeText(FlowRechargeActivity.this, "只支持联通", 0).show();
//				return;
//			}
			if ("".equals(proid)) {
				Toast.makeText(FlowRechargeActivity.this, "请选择要充值的金额", 0)
						.show();
			}
//			loginInfo = getLoginInfo();
			if (usrSP != null
					&& !(TextUtils.isEmpty(usrSP.getLogintoken()))) {
				if (mobileno != null && proid != null) {
					startThreadFlow();
				}
			} else {
				Intent inten3 = new Intent(FlowRechargeActivity.this,
						LoginActivity.class);
				startActivity(inten3);
			}
			break;
		case R.id.tv_nationwide:
			tv_nationwide.setBackgroundResource(R.drawable.bg_province_red_caipiao);
			tv_province.setBackgroundResource(R.drawable.bg_province_caipiao);
			if(lock == true){
				adapter = new MyAdapter(module.list1);
				lv_list2.setAdapter(adapter);
			}
			
			break;
		case R.id.tv_province:
			if (mobileno!=null) {
			tv_province.setBackgroundResource(R.drawable.bg_province_red_caipiao);
			tv_nationwide.setBackgroundResource(R.drawable.bg_province_caipiao);
			
				adapter = new MyAdapter(module.list);
				lv_list2.setAdapter(adapter);
			}else {
				Toast.makeText(this, "请先输入手机号码", 0).show();
			}
				
			break;
		case R.id.ll_record:
//			loginInfo = getLoginInfo();
			if (usrSP != null
					&& !(TextUtils.isEmpty(usrSP.getLogintoken()))) {
				Intent intent = new Intent(FlowRechargeActivity.this, MyFlowActivity.class);
				startActivity(intent);
			} else {
				Intent inten3 = new Intent(FlowRechargeActivity.this, LoginActivity.class);
				startActivity(inten3);
			}
			break;
		}
	}
}
